/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.client.sensor.area;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import nl.cloudfarming.client.logging.AppLogFactory;
import nl.cloudfarming.client.logging.AppLogger;
import nl.cloudfarming.client.model.Field;
import nl.cloudfarming.client.sensor.SensorEventKey;
import nl.cloudfarming.eventbus.BaseGuiEventProducer;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;

/**
 *
 * @author Timon Veenstra
 */
public class LinkSensorTask implements Runnable {

    private static final String LOG_MESSAGE_START = "link.message.info.start";
    private static final String LOG_MESSAGE_END = "link.message.info.end";
    private static final String LOG_MESSAGE_NO_PLOTS = "link.message.info.no.plots";
    private static final AppLogger LOG = AppLogFactory.getLogger(LinkSensorTask.class);
    private static final String PROCESS_TITLE = NbBundle.getMessage(LinkSensorTask.class, "link.process.title");
    private SensorAreaService service;
    
    private final ExecutorService pool;

    public LinkSensorTask(ExecutorService pool) {
        this.pool = pool;
    }
    
    

    @Override
    public void run() {
        LOG.info(LOG_MESSAGE_START);
        final List<Field> fields = getService().findAllFields();
        if (!fields.isEmpty()) {
            final InternalProgressHandle progessHandle = new InternalProgressHandle();
            progessHandle.start(fields.size());

            for (Field field : fields) {
                LinkSensorFieldFuture f = new LinkSensorFieldFuture(new LinkSensorFieldTask(field), new Callback() {

                    @Override
                    public void done() {
                        if (progessHandle.increment()) {
                            progessHandle.finish();
                            new EventProducer().triggerEvent(SensorEventKey.SENSOR_DATA_LINKED);
                            LOG.info(LOG_MESSAGE_END);
                        }
                    }
                });
                pool.submit(f);
            }

        } else {
            LOG.info(LOG_MESSAGE_NO_PLOTS);
        }
        pool.shutdown(); // Disable new tasks from being submitted
        try {
            // Wait a while for existing tasks to terminate
            if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                    System.err.println("Pool did not terminate");
                }
            }
        } catch (InterruptedException ie) {
            // (Re-)Cancel if current thread also interrupted
            pool.shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }

    }

    static interface Callback {

        void done();
    }
    
    private class EventProducer extends BaseGuiEventProducer {
        public EventProducer() {
            super(SensorEventKey.class);
        }
    }

    public SensorAreaService getService() {
        if (service == null){
            service = Lookup.getDefault().lookup(SensorAreaService.class);
        }
        if (service == null){
            service = new SensorAreaService();
        }        
        return service;
    }

    public void setService(SensorAreaService service) {
        this.service = service;
    }
    
  /**
     * internal progress handle to make interception possible
     */
    class InternalProgressHandle{
        private ProgressHandle intern;
        private int totalUnits;
        private int processedUnits;

        public InternalProgressHandle() {
            intern = ProgressHandleFactory.createHandle(PROCESS_TITLE);
        }
        
        public void start(int workunits){
            intern.start(workunits);
            totalUnits = workunits;
        }
        
        public boolean  increment(){
            intern.progress(++processedUnits);
            return processedUnits == totalUnits;
        }        
        
        public void finish(){
            intern.finish();
        }        
    }    
    
}
